package cn.samir.sudoku.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.util.Base64;

/**
 * 数据库工具，只支持基本数据类型
 * 
 * @author xin
 * 
 */
public class BeanUtils {

	private static final String TAG = "DBUtils";
	public static boolean isIdAutoInc = true;

	@SuppressLint("DefaultLocale")
	public static String getCreateTableSql(Class<?> clazz) {
		StringBuilder sb = new StringBuilder();
		Field[] fields = clazz.getDeclaredFields();
		sb.append("CREATE TABLE IF NOT EXISTS ");
		// getName 获得的是加上包名
		String clazzName = clazz.getSimpleName().toLowerCase(
				Locale.getDefault());
		sb.append(clazzName);
		sb.append("(");
		for (Field field : fields) {
			String fieldName = field.getName();
			if (fieldName.equals("_id")) {
				if (isIdAutoInc) {
					sb.append(fieldName + " INTEGER PRIMARY KEY AUTOINCREMENT,");
				} else {
					sb.append(fieldName + " INTEGER PRIMARY KEY ,");
				}
				continue;
			} else {
				sb.append(fieldName);
			}
			Class<?> type = field.getType();
			if (type == int.class || type == Integer.class) {
				sb.append(" INTEGER");
			} else if (type == Long.class || type == long.class) {
				sb.append(" LONG");
			} else if (type == Float.class || type == float.class) {
				sb.append(" FLOAT");
			} else if (type == String.class) {
				sb.append(" VARCHAR(250)");
			}
			sb.append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		sb.append(")");
		return sb.toString();
	}

	public static ContentValues BeanToValues(Object o) {
		if (o == null)
			return null;
		ContentValues values = new ContentValues();
		Class<? extends Object> clazz = o.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (Field filed : fields) {
			filed.setAccessible(true);
			String name = filed.getName();
			if ("_id".equals(name) || "id".equals(name)) {
				// 主键id 设置为null
				continue;
			}
			try {
				String obj = filed.get(o) + "";
				values.put(name, obj);
				LogUtils.i(TAG, name + "::" + obj);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return values;
	}

	/**
	 * 封装bean 支持基本数据类型
	 * 
	 * @param cursor
	 * @param clazz
	 * @return
	 */
	@SuppressLint("DefaultLocale")
	public static <T> T cursorToBean(Cursor cursor, Class<T> clazz) {
		Field[] fileds = clazz.getDeclaredFields();

		T obj = null;
		try {
			obj = clazz.newInstance();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
		for (Field field : fileds) {
			String key = field.getName();
			String column = key;
			LogUtils.i(TAG, "key=" + column);
			if (field.getType().equals(Integer.class)
					|| field.getType().equals(int.class)) {
				int index = cursor.getColumnIndex(column);
				if (index < 0) {
					continue;
				}
				int value = cursor.getInt(cursor.getColumnIndex(column));
				setProperty(obj, key, value);
				LogUtils.i(TAG, "value=" + value);
			} else if (field.getType().equals(Long.class)
					|| field.getType().equals(long.class)) {
				int index = cursor.getColumnIndex(column);
				if (index < 0) {
					continue;
				}
				long value = cursor.getLong(index);
				setProperty(obj, key, value);
				LogUtils.i(TAG, "value=" + value);
			} else if (field.getType().equals(Double.class)
					|| field.getType().equals(double.class)) {
				int index = cursor.getColumnIndex(column);
				if (index < 0) {
					continue;
				}
				double value = cursor.getDouble(cursor.getColumnIndex(column));
				setProperty(obj, key, value);
				LogUtils.i(TAG, "value=" + value);
			} else if (field.getType().equals(Float.class)
					|| field.getType().equals(float.class)) {
				int index = cursor.getColumnIndex(column);
				if (index < 0) {
					continue;
				}
				float value = cursor.getFloat(cursor.getColumnIndex(column));
				setProperty(obj, key, value);
				LogUtils.i(TAG, "value=" + value);
			} else if (field.getType().equals(String.class)) {
				int index = cursor.getColumnIndex(column);
				if (index < 0) {
					continue;
				}
				String value = cursor.getString(cursor.getColumnIndex(column));
				setProperty(obj, key, value);
				LogUtils.i(TAG, "value=" + value);
			} else if (field.getType().equals(Boolean.class)
					|| field.getType().equals(boolean.class)) {
				int index = cursor.getColumnIndex(column);
				if (index < 0) {
					continue;
				}
				setProperty(obj, key, cursor.getInt(cursor
						.getColumnIndex(column)) == 0 ? false : true);
			}

		}

		return obj;
	}

	/**
	 * 添加屬性
	 * 
	 * @param o
	 * @param field
	 * @param value
	 */
	public static void setProperty(Object o, String field, Object value) {
		try {
			Field f = o.getClass().getDeclaredField(field);
			f.setAccessible(true);
			f.set(o, value);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 编码文件
	 * 
	 * @param file
	 * @return
	 */
	public static String NotImageToBase64(File file) {
		String uploadBuffer = null;
		InputStream in = null;
		ByteArrayOutputStream bStream = null;
		try {
			in = new FileInputStream(file);
			bStream = new ByteArrayOutputStream();
			byte[] b = new byte[1024 * 8];
			int len = 0;
			while ((len = in.read(b)) > 0) {
				bStream.write(b, 0, len);
			}

			byte[] bytes = bStream.toByteArray();
			uploadBuffer = Base64.encodeToString(bytes, Base64.DEFAULT);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
					in = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (bStream != null) {
				try {
					bStream.close();
					bStream = null;
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}
		return uploadBuffer;
	}

	public static HashMap<String, String> beanToMaps(Object o) {
		if (o == null)
			return null;
		HashMap<String, String> values = new HashMap<String, String>();
		Class<? extends Object> clazz = o.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (Field filed : fields) {
			filed.setAccessible(true);
			String name = filed.getName();
			try {
				String obj = (String) (filed.get(o) + "");
				values.put(name, obj);
				LogUtils.i(TAG, name + "::" + obj);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return values;
	}

}
